package com.itao.bytebuddy;

import com.itao.util.ResourceUtil;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.implementation.FixedValue;

import java.io.File;
import java.io.IOException;

import static net.bytebuddy.matcher.ElementMatchers.named;

/**
 * @Author sjt
 * @CreateTime 2023/10/16 13:57
 */
public class InterceptMethod {
    public static void main(String[] args) {
        try (
                var unloaded = new ByteBuddy()
                        // 修改SupperClass,
                        // 将修改SupperClass类中的parent重名并保留，（parent$original$CE65kAX2）
                        // 并生成一个新的parent方法,返回值为sub
                        //.rebase(SupperClass.class)
                        // 修改SupperClass,
                        // 将修改SupperClass类中的parent,不保留原方法
                        .redefine(SupperClass.class)
                        //.name("com.itao.bytebuddy.SubClass")
                        // 拦截的方法
                        .method(named("parent"))
                        // 返回值为sub
                        .intercept(FixedValue.value("sub"))
                        .make()
        ) {
            unloaded.saveIn(new File(ResourceUtil.getClassPath(CreateClass.class)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
